package tech.realcpf.duckengine1.duckdb;

import org.apache.arrow.c.ArrowArrayStream;
import org.duckdb.DuckDBConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DuckDBInstance {

    private static final Logger LOGGER = LoggerFactory.getLogger(DuckDBInstance.class);

    private final String tenantId;

    private final String userId;

    private DuckDBConnection duckDBConnection;
    private final Properties prop;

    private volatile boolean init;

    public DuckDBInstance(String tenantId, String userId, Properties prop) {
        this.tenantId = tenantId;
        this.userId = userId;
        this.prop = prop;
    }

    public boolean connection(boolean readonly) throws SQLException {
        this.duckDBConnection = DuckDBConnection.newConnection("jdbc:duckdb:", readonly, prop);
        this.init = true;
        LOGGER.info("init duckdb connection [userId {} , tenantId {} ]", userId, tenantId);
        return this.duckDBConnection.isValid(1);
    }

    private void check() {
        if (!init) {
            throw new DuckInstanceException();
        }
    }

    public void exec(String sql) {
        LOGGER.info("duckdb exec sql \n{}",sql);
        try (PreparedStatement ps = duckDBConnection.prepareStatement(sql)) {
            ps.execute();
        } catch (Exception e) {
            throw new DuckInstanceException();
        }
    }

    public Object execWithProcessor(String sql, ResultProcessor processor) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("start duckdb [userId {} , tenantId {} ] sql {}", userId, tenantId, sql);
        }
        try (PreparedStatement ps = duckDBConnection.prepareStatement(sql)) {
            if (ps.execute()) {
                ResultSet rs = ps.getResultSet();
                return processor.process(rs, true);
            }
            return ps.getUpdateCount();
        } catch (Exception e) {
            LOGGER.error("error when [userId {} , tenantId {} ] exec sql {}", userId, tenantId, sql);
            return null;
        }
    }

}
